package com.newflypig.jblog.security;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.newflypig.jblog.service.ISystemService;

public class CustomUserDetailsAuthenticationProvider extends AbstractUserDetailsAuthenticationProvider {
	
	private ISystemService systemService;
	
	public void setSystemService(ISystemService systemService){
		this.systemService = systemService;
	}

	@Override
	protected void additionalAuthenticationChecks(UserDetails userDetails,
			UsernamePasswordAuthenticationToken authentication)
			throws AuthenticationException {
		//如果想做点额外的检查,可以在这个方法里处理,校验不通时,直接抛异常即可	
	}

	@Override
	protected UserDetails retrieveUser(String username,
			UsernamePasswordAuthenticationToken authentication)
			throws AuthenticationException {
		String password = authentication.getCredentials().toString();
		
		if( this.systemService.checkLogin(username, password) ){
			Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		    authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
		    authorities.add(new SimpleGrantedAuthority("ROLE_GUEST"));
		    UserDetails user = new User(username, "whatever", authorities);
		    return user;
		}
		
		if( this.systemService.checkGuest(username, password) ){
			Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		    authorities.add(new SimpleGrantedAuthority("ROLE_GUEST"));
		    UserDetails user = new User(username, "whatever", authorities);
		    return user;
		}
		
		throw new UsernameNotFoundException("");
	}
}
